package org.gg.boom.modules.sys.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.validation.Validator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.gg.boom.common.enums.DelFlagEnum;
import org.gg.boom.common.utils.ConvertUtils;
import org.gg.boom.common.utils.SecurityUtils;
import org.gg.boom.common.utils.StringUtils;
import org.gg.boom.common.utils.bean.BeanValidators;
import org.gg.boom.common.utils.spring.SpringUtils;
import org.gg.boom.kernel.annotation.DataScope;
import org.gg.boom.kernel.config.factory.PageFactory;
import org.gg.boom.kernel.exceptions.BizException;
import org.gg.boom.modules.sys.constant.UserConstants;
import org.gg.boom.modules.sys.mapper.SysPostMapper;
import org.gg.boom.modules.sys.mapper.SysRoleMapper;
import org.gg.boom.modules.sys.mapper.SysUserMapper;
import org.gg.boom.modules.sys.mapper.SysUserPostMapper;
import org.gg.boom.modules.sys.mapper.SysUserRoleMapper;
import org.gg.boom.modules.sys.model.entity.SysUser;
import org.gg.boom.modules.sys.model.entity.SysUserPost;
import org.gg.boom.modules.sys.model.entity.SysUserRole;
import org.gg.boom.modules.sys.model.param.SysUserParam;
import org.gg.boom.modules.sys.model.vo.SysPostResult;
import org.gg.boom.modules.sys.model.vo.SysRoleResult;
import org.gg.boom.modules.sys.model.vo.SysUserResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysUserService extends ServiceImpl<SysUserMapper, SysUser> {

    final SysRoleMapper roleMapper;

    final SysPostMapper postMapper;

    final SysUserRoleMapper userRoleMapper;

    final SysUserPostMapper userPostMapper;

    final SysConfigService configService;

    final Validator validator;

    /**
     * 根据条件分页查询用户列表
     *
     * @param param 用户信息
     * @return 用户信息集合信息
     */
    @DataScope(deptAlias = "d", userAlias = "u")
    public Page<SysUserResult> selectUserList(SysUserParam param) {
        Page<SysUserResult> page = baseMapper.selectUserList(PageFactory.defaultPage(), param);
        return page;
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param param 用户信息
     * @return 用户信息集合信息
     */
    @DataScope(deptAlias = "d", userAlias = "u")
    public Page<SysUserResult> selectAllocatedList(SysUserParam param) {
        return baseMapper.selectAllocatedList(PageFactory.defaultPage(), param);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param param 用户信息
     * @return 用户信息集合信息
     */
    @DataScope(deptAlias = "d", userAlias = "u")
    public Page<SysUserResult> selectUnallocatedList(SysUserParam param) {
        return baseMapper.selectUnallocatedList(PageFactory.defaultPage(), param);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    public SysUserResult selectUserByUserName(String userName) {
        return baseMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    public SysUserResult selectUserById(Long userId) {
        return baseMapper.selectUserById(userId);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    public String selectUserRoleGroup(String userName) {
        List<SysRoleResult> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRoleResult::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    public String selectUserPostGroup(String userName) {
        List<SysPostResult> list = postMapper.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPostResult::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    public boolean checkUserNameUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = baseMapper.checkUserNameUnique(user.getUserName());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    public boolean checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = baseMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    public boolean checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = baseMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param userId 用户信息
     */
    public void checkUserAllowed(Long userId) {
        if (Objects.nonNull(userId) && userId == 1L) {
            throw new BizException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    public void checkUserDataScope(Long userId) {
        if (!UserConstants.isAdmin(SecurityUtils.getUserId())) {
            SysUserParam param = new SysUserParam();
            param.setUserId(userId);
            Page<SysUserResult> users = SpringUtils.getAopProxy(this).selectUserList(param);
            if (StringUtils.isEmpty(users.getRecords())) {
                throw new BizException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param param 用户信息
     * @return 结果
     */
    @Transactional
    public boolean insertUser(SysUserParam param) {
        SysUser sysUser = ConvertUtils.sourceToTarget(param, SysUser.class);
        sysUser.setDelFlag(DelFlagEnum.NOT_DELETE.getCode());
        // 新增用户信息
        boolean save = save(sysUser);
        // 新增用户岗位关联
        insertUserPost(param);
        // 新增用户与角色管理
        insertUserRole(param);
        return save;
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    public boolean registerUser(SysUser user) {
        return baseMapper.insertUser(user) > 0;
    }

    /**
     * 修改保存用户信息
     *
     * @param param 用户信息
     * @return 结果
     */
    @Transactional
    public boolean updateUser(SysUserParam param) {
        Long userId = param.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(param);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(param);
        SysUser sysUser = ConvertUtils.sourceToTarget(param, SysUser.class);
        return updateById(sysUser);
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     *
     * @param param 用户信息
     * @return 结果
     */
    public boolean updateUserStatus(SysUserParam param) {
        SysUser sysUser = ConvertUtils.sourceToTarget(param, SysUser.class);
        return updateById(sysUser);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    public int updateUserProfile(SysUser user) {
        return baseMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    public boolean updateUserAvatar(String userName, String avatar) {
        return baseMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param param 用户信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean resetPwd(SysUserParam param) {
        Long[] userIds = param.getUserIds();
        if (userIds != null && userIds.length > 0) {
            List<SysUser> users = Arrays.stream(userIds).map(item -> {
                SysUser user = new SysUser();
                user.setUserId(item);
                user.setPassword(param.getPassword());
                return user;
            }).toList();
            return updateBatchById(users);
        }
        return false;
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    public int resetUserPwd(String userName, String password) {
        return baseMapper.resetUserPwd(userName, password);
    }

    /**
     * 新增用户角色信息
     *
     * @param param 用户对象
     */
    public void insertUserRole(SysUserParam param) {
        this.insertUserRole(param.getUserId(), param.getRoleIds());
    }

    /**
     * 新增用户岗位信息
     *
     * @param param 用户对象
     */
    public void insertUserPost(SysUserParam param) {
        Long[] posts = param.getPostIds();
        if (StringUtils.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = Arrays.stream(posts).map(postId -> {
                SysUserPost userPost = new SysUserPost();
                userPost.setUserId(param.getUserId());
                userPost.setPostId(postId);
                return userPost;
            }).collect(Collectors.toList());
            userPostMapper.batchUserPost(list);
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = Arrays.stream(roleIds).map(roleId -> {
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                return userRole;
            }).collect(Collectors.toList());
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Transactional
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return baseMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Transactional
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(userId);
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return baseMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new BizException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = getUserByUsername(user.getUserName());
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    baseMapper.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(u.getUserId());
                    checkUserDataScope(u.getUserId());
                    user.setUserId(u.getUserId());
                    user.setUpdateBy(operName);
                    baseMapper.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BizException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    public SysUser getUserByUsername(String username) {
        return getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserName, username));
    }
}
